package com.kmzx.one.project.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kmzx.one.common.utils.UUIDGenerator;
import com.kmzx.one.project.entity.AttributeWithCategory;
import com.kmzx.one.project.entity.Product;
import com.kmzx.one.project.entity.ProductSource;
import com.kmzx.one.project.entity.SourceUserDown;
import com.kmzx.one.project.entity.SourceUserStore;
import com.kmzx.one.project.mapper.CustomerMapper;
import com.kmzx.one.project.mapper.MaterialMapper;
import com.kmzx.one.project.mapper.ProductMapper;
import com.kmzx.one.project.mapper.UserRankMapper;
import com.kmzx.one.project.others.common.CarouselsImgWH;
import com.kmzx.one.project.others.common.IdAndKinds;
import com.kmzx.one.project.others.common.IdAndTitle;
import com.kmzx.one.project.others.dso.ProdJoinAttributeWithCategory;
import com.kmzx.one.project.others.dso.ProdJoinDiscount;
import com.kmzx.one.project.others.dto.MateCateOutInfo;
import com.kmzx.one.project.others.dto.MateOutInfo;
import com.kmzx.one.project.others.dto.MaterialDetailInfo;
import com.kmzx.one.project.others.dto.MemberActionInfo;
import com.kmzx.one.project.others.dto.PagedMateOutInfo;
import com.kmzx.one.project.others.dto.UserMateOutInfo;
import com.kmzx.one.project.others.dto.UserRankInfo;
import com.kmzx.one.project.service.MaterialService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MaterialServiceImpl implements MaterialService {
    private static final Logger logger = LoggerFactory.getLogger(MaterialServiceImpl.class);
    @Autowired
    MaterialMapper materialMapper;


    @Autowired
    private CustomerMapper customerMapper;


    @Autowired
    private ProductMapper productMapper;

    @Autowired
    UserRankMapper userRankMapper;


    @Override
    public List<MateCateOutInfo> findAllMaterialCategory(String userId) throws Exception {
        MateCateOutInfo outInfo = new MateCateOutInfo();
        outInfo.setCateId("__all__").setCateName("全部").setSeria(-2);
        List<MateCateOutInfo> infos = materialMapper.selectAllMateCateInfo();
        if (infos != null) {
            infos.add(outInfo);
            infos.sort(Comparator.comparing(MateCateOutInfo::getSeria));
            return infos;
        } else {
            ArrayList<MateCateOutInfo> outInfos = new ArrayList<>();
            outInfos.add(outInfo);
            return outInfos;
        }
    }

    @Override
    public PagedMateOutInfo findAllMaterialById(String cateId, Integer pageNum, Integer pageSize, String userId) throws Exception {
        //查找全部
        PagedMateOutInfo mate;
        if (cateId != null && "__all__".equals(cateId)) {
            PageHelper.startPage(pageNum, pageSize, true);
            Page<MateOutInfo> pe = materialMapper.findAllMaterial(pageNum, pageSize);
            mate = new PagedMateOutInfo(pe.getPageNum(), pe.getPageSize(), pe.getStartRow(), pe.getEndRow(), pe.getTotal(), pe.getPages());
            mate.setChildren(pe.getResult());

        } else {
            PageHelper.startPage(pageNum, pageSize, true);
            Page<MateOutInfo> pe = materialMapper.findAllMaterialById(cateId, pageNum, pageSize);
            mate = new PagedMateOutInfo(pe.getPageNum(), pe.getPageSize(), pe.getStartRow(), pe.getEndRow(), pe.getTotal(), pe.getPages());
            mate.setChildren(pe.getResult());

        }
        List<MateOutInfo> result = mate.getChildren();
        if (result != null && result.size() > 0) {
            List<String> mateIdList = result.stream().filter(mo -> mo.getKinds() == 1).map(ll -> ll.getMateId()).collect(Collectors.toList());
            if (mateIdList != null && mateIdList.size() > 0) {
                List<IdAndTitle> titles = materialMapper.selectMateVideoUrl(mateIdList);
                for (MateOutInfo info : result) {
                    String pic = info.getMateOssUrl();
                    int dot = pic.lastIndexOf(".");
                    int subLine = pic.lastIndexOf("_");
                    String[] xes = pic.substring(subLine + 1, dot).split("×");
                    info.setWidth(Integer.valueOf(xes[0]));
                    info.setHeight(Integer.valueOf(xes[1]));


                    for (IdAndTitle title : titles) {
                        if (info.getMateId().equals(title.getId())) {
                            info.setVideoUrl(title.getTitle());
                        }
                    }
                }
            }
        }
        mate.setChildren(result);
        return mate;
    }

    @Override
    public MaterialDetailInfo findAllMaterialDetail(String mateId, String userId) throws Exception {
        List<MaterialDetailInfo> detail = materialMapper.findAllMaterialDetail(mateId, userId);
        if (detail != null && detail.size() > 0) {
            List<String> list = detail.stream().map(md -> md.getPicUrl()).collect(Collectors.toList());
            MaterialDetailInfo info = detail.get(0);
            int cate = info.getOssKinds();
            info.setCarouselsImg(list);
            if (cate == 1) {
                String pic = list.get(0);
                int dot = pic.lastIndexOf(".");
                int subLine = pic.lastIndexOf("_");
                String[] xes = pic.substring(subLine + 1, dot).split("×");
                info.setWidth(Integer.valueOf(xes[0]));
                info.setHeight(Integer.valueOf(xes[1]));
                List<String> subList = list.subList(1, list.size());
                info.setCarouselsImg(subList);


                CarouselsImgWH wh = new CarouselsImgWH();

                wh.setWidth(Integer.valueOf(xes[0]));
                wh.setHeight(Integer.valueOf(xes[1]));
                wh.setUrl(subList.get(0));
                wh.setType(1);
                List<CarouselsImgWH> whs = Arrays.asList(wh);
                info.setCarouselsImgWH(whs);

                info.setMaxHeight(wh.getHeight());
                info.setMaxWidth(wh.getWidth());


            } else {
//                String picUrl = info.getPicUrl();
//                int subLine = picUrl.lastIndexOf("_");
//                int dot = picUrl.lastIndexOf(".");
//                String[] xes = picUrl.substring(subLine + 1, dot).split("×");
//                info.setWidth(Integer.valueOf(xes[0]));
//                info.setHeight(Integer.valueOf(xes[1]));
                int max = 0;
                int maxW = 0;
                ArrayList<CarouselsImgWH> whs = new ArrayList<>();
                for (String s : list) {
                    CarouselsImgWH wh = new CarouselsImgWH();
                    int subLineI = s.lastIndexOf("_");
                    int dotI = s.lastIndexOf(".");
                    String[] xesI = s.substring(subLineI + 1, dotI).split("×");
                    wh.setWidth(Integer.valueOf(xesI[0]));
                    wh.setHeight(Integer.valueOf(xesI[1]));
                    int height = wh.getHeight();
                    if (max <= height) {
                        max = height;
                    }
                    if (maxW < wh.getWidth()) {
                        maxW = wh.getWidth();
                    }
                    wh.setUrl(s);
                    wh.setType(0);
                    whs.add(wh);
                }
                info.setMaxHeight(max);
                info.setMaxWidth(maxW);
                info.setCarouselsImgWH(whs);

            }


            String prodId = info.getProdId();

            if (prodId != null && !"".equals(prodId)) {
                Product product = productMapper.selectProdById(prodId);
                info.setProdName(product.getProductName());

                List<IdAndKinds> pics = productMapper.selectProdPicsByProdId(prodId);
                if (!CollectionUtils.isEmpty(pics)) {
                    List<IdAndKinds> collect = pics.stream().filter(a -> a.getKinds() == 0).collect(Collectors.toList());
                    if (collect != null && collect.size() > 0) {
                        String id = collect.get(0).getId();
                        info.setProdImg(id);
                    }

                }
                boolean has = false;
                List<String> specUsers = customerMapper.findSpecificUser();

                if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "")) {

                    if (specUsers.contains(userId)) {
                        // 有特权,有用户,也是
                        has = true;
                    } else { // 有特权,有用户,但不是
                        has = false;
                    }
                } else {
                    // 没特权,没用户
                    // 有特权,没用户
                    has = false;
                }


                List<ProdJoinAttributeWithCategory> joinAttributes = productMapper.selectProdEntryInfo2(prodId);
                // 所有的商品打折活动,包括所有的商品
                List<ProdJoinDiscount> discounts = productMapper.selectProductJoinDiscount(prodId);
                if (!CollectionUtils.isEmpty(joinAttributes)) {
                    ProdJoinAttributeWithCategory joinAttribute = joinAttributes.get(0);

                    info.setEnabled(joinAttribute.getStates());
                    Integer inOrOut = joinAttribute.getInOrOut();
                    info.setInOrOut(inOrOut);
                    info.setProdPrice(joinAttributes.stream().sorted(Comparator.comparing(ProdJoinAttributeWithCategory::getPrice)).findFirst().get().getPrice());
                    info.setCurrentPrice(info.getProdPrice());
                    info.setBeauty(info.getCurrentPrice());

                    if (discounts != null && discounts.size() > 0) {
                        Map<String, List<ProdJoinDiscount>> listMap = discounts.stream().collect(Collectors.groupingBy(ProdJoinDiscount::getProductId));
                        List<ProdJoinDiscount> discountList = listMap.get(prodId);
                        if (discountList != null && discountList.size() > 0) {

                            for (ProdJoinDiscount joinDiscount : discountList) {
                                Integer discountCate = joinDiscount.getDiscountCate();
                                if (discountCate == 0) {
                                    joinDiscount.setCurrentPrice(info.getProdPrice().multiply(joinDiscount.getDiscountNum()));
                                } else if (discountCate == 1 || discountCate == 2) {
                                    joinDiscount.setCurrentPrice(joinDiscount.getDiscountNum());
                                } else if (discountCate == 3) {
                                    joinDiscount.setCurrentPrice(joinDiscount.getDiscountNum());
                                    info.setTefan(2);
                                }
                            }
                            discountList.sort(Comparator.comparing(ProdJoinDiscount::getCurrentPrice));


                            ProdJoinDiscount discount = discountList.get(0);

                            // 固定折扣
                            info.setKinds(1);
                            BigDecimal currentPrice = info.getCurrentPrice();
                            info.setDiscountImg(discount.getDiscountImg());
                            if (discount.getDiscountCate() == 0) {
                                if (discount.getDiscountNum().compareTo(BigDecimal.ONE) == 0) {
                                    info.setKinds(0);
                                }
                                info.setCurrentPrice(currentPrice.multiply(discount.getDiscountNum()));
                            } else {
                                info.setCurrentPrice(discount.getDiscountNum());
                            }
                            Integer special = discount.getSpecial();
                            if (special != null && special == 0) {
                                if (discount.getDiscountCate() == 2) {
                                    info.setCurrentPrice(discount.getDiscountNum());
                                    info.setOneValue(true);
                                }
                            }

                            info.setBeauty(info.getCurrentPrice());
                        }
                    }

//                    BigDecimal minPrice = productMapper.findProductSpecificMinPrice(prodId);
                    String minPriceAs = productMapper.findProductSpecificMinPriceAs(prodId);
                    if (has && minPriceAs != null) {
                        // 特权的最小价格

                        String[] split = minPriceAs.split("@");
                        String skuId = split[0];
                        String minPriceStr = split[1];
                        // 特权的最小价格
                        AttributeWithCategory id = productMapper.selectAttributeWithCategoryById(skuId);
                        Integer prodNum = id.getProdNum();
                        BigDecimal minPrice = new BigDecimal(minPriceStr).multiply(BigDecimal.valueOf(prodNum));
                        info.setCurrentPrice(minPrice);
                        info.setProdPrice(minPrice);
                        info.setBeauty(minPrice);
                    } else {
                        // 直升商品
                        int rankUp1 = 0;
                        List<MemberActionInfo> actionInfos = productMapper.selectProductStraight();
                        if (!CollectionUtils.isEmpty(actionInfos)) {
                            List<Map<String, Object>> lists = productMapper.selectProdFastKind(prodId, 0);

                            if (!CollectionUtils.isEmpty(lists)) {
                                for (Map<String, Object> objectMap : lists) {
                                    Double growthValue = (Double) objectMap.get("growthValue");
                                    info.setBeauty(BigDecimal.valueOf(growthValue));
                                    BigDecimal upMoney = (BigDecimal) objectMap.get("upMoney");
                                    info.setCurrentPrice(upMoney);
                                    rankUp1 = (Integer) objectMap.get("rankNum");
                                    info.setKinds(2);
                                    info.setFastIcon((String) objectMap.get("picOne"));
                                    info.setBeauty(info.getCurrentPrice());
                                }
                            }
                        }
                        //
                        if (!info.isOneValue()) {

                            UserRankInfo rankInfo = userRankMapper.selectUserRankTabs(userId);

                            if (rankInfo != null) {
                                if (rankInfo.getRankNum() > 0 && rankInfo.getRankNum() > rankUp1) {
                                    int kinds = info.getKinds();
                                    if (kinds == 2) {
                                        info.setRankPrice(info.getProdPrice().multiply(rankInfo.getBigRankRate()));
                                    } else {
                                        info.setRankPrice(info.getCurrentPrice().multiply(rankInfo.getBigRankRate()));
                                    }
                                    info.setRankNum(rankInfo.getRankNum());
                                    info.setRankIcon(rankInfo.getPriceIcon());
                                }
                            }

                            if(info.getTefan()==2){
                                info.setRankIcon("").setRankPrice(BigDecimal.ZERO);
                            }
                        }

                    }
//                    Map<String, BigDecimal> freeFee = productMapper.selectProductFreeFee();
                    Integer isBehalf = product.getIsBehalf();
                    if (isBehalf != null) {
                        if (isBehalf == 0) {
                            info.setHas(true);
                        } else {
                            Integer po = productMapper.selectProdAttributeStoreId3(prodId);
                            if (po != null && po != 0) {
                                info.setHas(true);
                            }
                        }
                    } else {
                        Integer po = productMapper.selectProdAttributeStoreId3(prodId);
                        if (po != null && po != 0) {
                            info.setHas(true);
                        }
                    }

                }

            } else {
                info.setProdId(null);
            }
            // 收藏
            List<SourceUserStore> storeList = materialMapper.selectSourceStore(mateId);
            if (storeList == null) {
                info.setStoreNum(0);
                info.setStore(false);
            } else {
                info.setStoreNum(storeList.size());
                if (userId != null && !"".equals(userId)) {
                    long count = storeList.stream().filter(ob -> ob.getUserId().equals(userId)).count();
                    if (count > 0) {
                        info.setStore(true);
                    }
                }
            }
            return info;
        }
        return null;
    }

    @Override
    public UserMateOutInfo findUserMaterialStore(String userId, Integer pageNum, Integer pageSize) {
        Page<Object> objects = PageHelper.startPage(pageNum, pageSize, true);
        Page<MateOutInfo> pe = materialMapper.findUserMaterial(userId);
        UserMateOutInfo outInfo = new UserMateOutInfo(pe.getPageNum(), pe.getPageSize(), pe.getStartRow(), pe.getEndRow(), pe.getTotal(), pe.getPages());
        List<MateOutInfo> result = pe.getResult();
        if (result != null && result.size() > 0) {
            List<String> mateIdList = result.stream().filter(mo -> mo.getKinds() == 1).map(ll -> ll.getMateId()).collect(Collectors.toList());
            if (mateIdList != null && mateIdList.size() > 0) {
                List<IdAndTitle> titles = materialMapper.selectMateVideoUrl(mateIdList);
                for (MateOutInfo info : result) {
                    String pic = info.getMateOssUrl();
                    int subLine = pic.lastIndexOf("_");
                    int dot = pic.lastIndexOf(".");
                    String[] xes = pic.substring(subLine + 1, dot).split("×");
                    info.setHeight(Integer.valueOf(xes[1]));
                    info.setWidth(Integer.valueOf(xes[0]));

                    for (IdAndTitle title : titles) {
                        if (info.getMateId().equals(title.getId())) {
                            info.setVideoUrl(title.getTitle());
                        }
                    }
                }
            }
        }

        outInfo.setChildren(result);
        outInfo.setUserId(userId);
        return outInfo;
    }

    @Override
    public int doUserMaterialStore(String mateId, String userId) {
        List<SourceUserStore> stores = materialMapper.selectSourceUserStore(userId, mateId);
        if (stores != null && stores.size() > 0) {
            SourceUserStore store = stores.get(0);
            if (store.getStates() == 1) {
                store.setStates(0).setDeleted(1);
                Date updateTime = new Date();
                store.setUpdateTime(updateTime);
                logger.info("取消收藏素材");
                materialMapper.updateSourceStoreById(store);
                materialMapper.storeMaterial(mateId, 2);
                logger.info("取消收藏素材OK");
            }
        } else {
            ProductSource source = materialMapper.selectProductSourceById(mateId);
            Date updateTime = new Date();
            SourceUserStore sourceUserStore = new SourceUserStore();
            sourceUserStore.setId(UUIDGenerator.generate()).setUserId(userId).setProductSourceId(mateId)
                    .setDeleted(0).setStates(1).setCreateTime(updateTime).setUpdateTime(updateTime);
            sourceUserStore.setIsChange(source.getIsChange()).setProductId(source.getProductId());

            logger.info("新增收藏素材");
            materialMapper.insertUserMaterialStore(sourceUserStore);
            materialMapper.storeMaterial(mateId, 1);
            logger.info("新增收藏素材OK");
        }

        return 0;
    }

    @Override
    public int downloadMaterial(String mateId, String userId) {
        if (userId == null || "".equals(userId)) {
            logger.info("新增下载素材");
        } else {
            SourceUserDown down = new SourceUserDown();
            down.setId(UUIDGenerator.generate()).setCreateTime(new Date()).setUpdateTime(new Date())
                    .setProductSourceId(mateId).setStates(1).setUserId(userId);
            ProductSource source = materialMapper.selectProductSourceById(mateId);
            down.setProductId(source.getProductId());
            logger.info("新增下载素材");
            materialMapper.insertUserMaterialDown(down);
            materialMapper.downloadMaterial(mateId, 1);
            logger.info("新增下载素材OK");
        }
        return 0;
    }


}
